﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Linq;

namespace System.Xml.Serialization
{
    /// <summary>
    /// 针对<see langword="System.Xml"/>进行扩展
    /// </summary>
    /// <creator>marc</creator>
    public static class XmlExtensions
    {
        /// <summary>
        /// 将对象序列化为XML字符串
        /// </summary>
        public static string ToXml<T>(this T obj)
        {
            var serializer = new XmlSerializer(typeof(T));

            using (var writer = new StringWriter())
            {
                serializer.Serialize(writer, obj);
                return writer.ToString();
            }
        }

        /// <summary>
        /// 将XML字符串反序列化为对象
        /// </summary>
        public static T FromXml<T>(this string xml)
        {
            var serializer = new XmlSerializer(typeof(T));

            using (var reader = new StringReader(xml))
            {
                return (T)serializer.Deserialize(reader);
            }
        }

        /// <summary>
        /// 将对象序列化为XML字节数组
        /// </summary>
        public static byte[] ToXmlBytes<T>(this T obj, Encoding encoding = null)
        {
            //encoding ??= Encoding.UTF8;
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            //using (var memoryStream = new MemoryStream())
            //{
            //    var serializer = new XmlSerializer(typeof(T));
            //    serializer.Serialize(memoryStream, obj);
            //    return memoryStream.ToArray();
            //}
            using (var memoryStream = new MemoryStream())
            using (var writer = new StreamWriter(memoryStream, encoding))
            {
                var serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(writer, obj);
                return memoryStream.ToArray();
            }
        }

        /// <summary>
        /// 将XML字节数组反序列化为对象
        /// </summary>
        public static T FromXmlBytes<T>(this byte[] xmlBytes, Encoding encoding = null)
        {
            //encoding ??= Encoding.UTF8;
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            //using (var memoryStream = new MemoryStream(xmlBytes))
            //{
            //    var serializer = new XmlSerializer(typeof(T));
            //    return (T)serializer.Deserialize(memoryStream);
            //}

            using (var memoryStream = new MemoryStream(xmlBytes))
            using (var reader = new StreamReader(memoryStream, encoding))
            {
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(reader);
            }
        }
    }
}
